package cn.lavender.web.configuration.http;

import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * RestTemplate的配置类
 * </p>
 * @author: zhu.chen
 * @date: 2021/3/18
 * @version: v1.0.0
 */
@Configuration
@EnableConfigurationProperties({RestClientProperties.class})
public class RestTemplateAutoConfigure {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory requestFactory(HttpClientBuilder builder, RestClientProperties restClientProperties) {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(restClientProperties.getConnectionTimeout());
        factory.setReadTimeout(restClientProperties.getReadTimeout());
        // 连接不够用的等待时间，不宜过长，必须设置，比如连接不够用时，时间过长将是灾难性的
        factory.setConnectionRequestTimeout(restClientProperties.getConnectionRequestTimeout());
        factory.setHttpClient(builder.build());
        return factory;
    }

    @Bean
    public HttpClientBuilder httpClientBuilder(HttpClientConnectionManager manager) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(manager);
        // 设置重定向规则，自动获取重定向内容
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
        return httpClientBuilder;
    }

    @Bean
    public HttpClientConnectionManager connectionManagerConfig(RestClientProperties restClientProperties) {
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        //每个主机的并发
        manager.setDefaultMaxPerRoute(restClientProperties.getDefaultMaxPerRoute());
        //整个连接池的并发
        manager.setMaxTotal(restClientProperties.getMaxTotal());
        return manager;
    }

}
